package com.ddstation.hzsc_invs.system_setting.controller;

import com.ddstation.common.util.AliCloudOssUtil;
import com.ddstation.crm.institution.entity.DtHealthManageInstitutionDoctorEntity;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.crm.login.service.LoginAccountService;
import com.ddstation.crm.login.util.ValidateUtil;
import com.ddstation.crm.login.util.WnSessionUtil;
import com.ddstation.crm.menu.mapper.DtInvsManageInstitutionMenuMinusMapper;
import com.ddstation.crm.organization_structure.entity.DtInvsOrganizationStructureEntity;
import com.ddstation.crm.organization_structure.entity.DtInvsOrganizationStructureStaffEntity;
import com.ddstation.crm.organization_structure.mapper.DtInvsOrganizationStructureMapper;
import com.ddstation.crm.organization_structure.mapper.DtInvsOrganizationStructureStaffMapper;
import com.ddstation.crm.organization_structure.service.OrgService;
import com.ddstation.crm.organization_structure.service.StaffService;
import com.ddstation.crud.entity.DtInvsManageInstitutionSupervisorEntity;
import com.ddstation.crud.mapper.DtInvsManageInstitutionSupervisorMapper;
import com.ddstation.doctor.entity.DdDoctorEntity;
import com.ddstation.security.util.WnBizMsgCrypt;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统设置-杭州上城
 */
@Controller @Lazy
public class SystemSettingController {

	/**
	 * 获取部门下用户列表
	 * @return
	 */
	@RequestMapping(value="invs_system_setting.do/getUserList", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> listStaffEvent(
			@RequestParam("orgId")int orgId) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errCode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		List<DtInvsOrganizationStructureStaffEntity> staffs = staffService.getCoverStaff(orgId);
		if (staffs != null) {
			for (DtInvsOrganizationStructureStaffEntity staff : staffs) {
				staff.setDoctorUUID(WnBizMsgCrypt.encrypt(staff.getDoctor().getId()));// doctorid 加密
				//隐藏名称前缀
				DtHealthManageInstitutionDoctorEntity account = staff.getAccount();
				String loginUser = account.getLoginUser();
				account.setLoginUser(loginUser.indexOf("invs_") == 0 ? loginUser.substring(5, loginUser.length()) : loginUser);
				staff.setAccount(account);
				//判断权限
				if (staff.getNoJurisdictionCount() == 0) {
					//全部权限
					staff.setJurisdiction("all");
					staff.setJurisdictionName("全部");
				} else {
					//字符替换
					String jurisdictionName = staff.getJurisdictionName();
					if (jurisdictionName != null) {
						staff.setJurisdictionName(jurisdictionName.replace(",", "、"));
					} else {
						staff.setJurisdictionName("无");
					}
				}
				//头像URL
				DdDoctorEntity doctor = staff.getDoctor();
				String headImgUrl = AliCloudOssUtil.getOriginImgUrl(null,doctor.getHeadImgUrl());
				doctor.setHeadImgUrl(headImgUrl);
				staff.setDoctor(doctor);
			}
		}
		ret.put("staffs", staffs);
		//查询部门权限
		List<DtInvsOrganizationStructureEntity> organizationStructureList = dtInvsOrganizationStructureMapper.selectJurisdictionByOgrId(orgId);
		ret.put("orgJurisdictionList", organizationStructureList);

		ret.put("errCode", 1);
		ret.put("errMsg", "操作成功！");
		return ret;
	}

	/**
	 * 部门权限设置
	 * @return
	 */
	@RequestMapping(value="invs_system_setting.do/updateOrgJurisdiction", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> updateOrgJurisdiction(HttpSession session,
			@RequestParam("orgId")int orgId,
			@RequestParam("orgName") String orgName,
			@RequestParam(value="menuIdList[]",required=false) List<Integer> menuIdList) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errCode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		String institutionId = WnSessionUtil.getInstitutionId(session);
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if(loginData.getIsManager() != 2) {
			ret.put("errMsg", "权限不足");
			return ret;
		}
		//修改部门名称
		DtInvsOrganizationStructureEntity orgStruct = new DtInvsOrganizationStructureEntity();
		orgStruct.setId(orgId);
		orgStruct.setName(orgName);
		orgStruct.setInstitutionId(institutionId);
		orgService.replace(orgStruct);
		//修改部门权限
		dtInvsManageInstitutionMenuMinusMapper.deleteByOrgId(institutionId,orgId,0,1);
		if(menuIdList != null){
			dtInvsManageInstitutionMenuMinusMapper.insertOnOrg(institutionId,orgId,menuIdList,1);
		}
		ret.put("errCode", 1);
		ret.put("errMsg", "操作成功！");
		return ret;
	}

	/**
	 * 添加部门
	 * @return
	 */
	@RequestMapping(value="invs_system_setting.do/addOrg", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> addOrg(HttpSession session,
		   @RequestParam("orgName") String orgName,
		   @RequestParam(value="menuIdList[]",required=false) List<Integer> menuIdList) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errCode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		String institutionId = WnSessionUtil.getInstitutionId(session);
		if(orgName == null || orgName.length() == 0){
			ret.put("errMsg", "部门名称不能为空！");
			return ret;
		}
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if(loginData.getIsManager() != 2) {
			ret.put("errMsg", "权限不足");
			return ret;
		}
		//获取顶级部门
		DtInvsOrganizationStructureEntity parent = dtInvsOrganizationStructureMapper.selectTopLevel(institutionId);
		//添加部门
		DtInvsOrganizationStructureEntity orgStruct = new DtInvsOrganizationStructureEntity();
		orgStruct.setName(orgName);
		orgStruct.setInstitutionId(institutionId);
		orgStruct.setParent(parent);
		orgService.add(orgStruct);
		//权限

		if (menuIdList != null) {
			dtInvsManageInstitutionMenuMinusMapper.insertOnOrg(institutionId,orgStruct.getId(),menuIdList,1);
		}

		ret.put("errCode", 1);
		ret.put("errMsg", "操作成功！");
		return ret;
	}

	/**
	 * 删除部门
	 * @return
	 */
	@RequestMapping(value="invs_system_setting.do/deleteOrg", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> deleteOrg(HttpSession session,
			@RequestParam("orgId") int orgId) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errCode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if(loginData.getIsManager() != 2) {
			ret.put("errMsg", "权限不足");
			return ret;
		}
		List<DtInvsOrganizationStructureStaffEntity> coverStaffs = staffService.getCoverStaff(orgId);
		if (coverStaffs != null && !coverStaffs.isEmpty()) {
			ret.put("errMsg", "该部门中存在成员, 无法删除！");
		} else {
			DtInvsOrganizationStructureEntity orgStruct = new DtInvsOrganizationStructureEntity();
			orgStruct.setId(orgId);
			orgStruct.setInstitutionId(WnSessionUtil.getInstitutionId(session));
			orgService.remove(orgStruct);
			ret.put("errCode", 1);
			ret.put("errMsg", "操作成功！");
		}
		return ret;
	}

	/**
	 * 添加用户
	 * @return
	 */
	@RequestMapping(value="invs_system_setting.do/addUser", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> addUser(HttpSession session,
			@RequestParam("orgId")int orgId,
			@RequestParam("infoImg") String infoImg,
			@RequestParam("name") String name,
			@RequestParam("cell") String cell,
			@RequestParam("loginName") String loginName,
			@RequestParam("loginPass") String loginPass,
			@RequestParam("isManager") int isManager,
			@RequestParam(value="menuIdList[]",required=false) List<Integer> menuIdList) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errCode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		String institutionId = WnSessionUtil.getInstitutionId(session);
		//参数校验
		if (cell.length() != 11) {
			ret.put("errMsg", "手机号格式不正确，请输入11位手机号");
			return ret;
		} else if (!ValidateUtil.chkLoginUserPw(loginName)) {
			ret.put("errMsg", "用户名需要由数字/字母/下划线组成");
			return ret;
		}
		int lnLength = loginName.length();
		if (lnLength < 3 || lnLength > 16) {
			ret.put("errMsg", "请输入3-16位用户名");
			return ret;
		} else if (!ValidateUtil.chkLoginUserPw(loginName)) {
			ret.put("errMsg", "用户名需要由数字/字母/下划线组成");
			return ret;
		}
		int pwLength = loginPass.length();
		if (pwLength < 6 || pwLength > 16) {
			ret.put("errMsg", "请输入6-16位密码");
			return ret;
		} else if (!ValidateUtil.chkLoginUserPw(loginPass)) {
			ret.put("errMsg", "密码需要由数字/字母/下划线组成");
			return ret;
		}
		//权限
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData.getIsManager() == 0) {
			ret.put("errMsg", "权限不足，无法执行操作");
			return ret;
		}else if(loginData.getIsManager() == 1 && loginData.getOrgId() != orgId) {
			ret.put("errMsg", "仅能操作所属部门下用户");
			return ret;
		}else if(loginData.getIsManager() == 1 && isManager == 1) {
			ret.put("errMsg", "管理员只能由超级账户添加");
			return ret;
		}

		DtInvsManageInstitutionSupervisorEntity supervisorEntity = dtInvsManageInstitutionSupervisorMapper.selectByUserName("invs_" + loginName);
		if (supervisorEntity != null) {
			ret.put("errMsg", "登录账户已经存在");
			return ret;
		} else {
			//图片上传OSS
			String ossUrl = AliCloudOssUtil.getUrlByBase64(null,infoImg);
			if(ossUrl == null || ossUrl.length() == 0){
				//默认头像，可替换
				ossUrl = "Uploads/Picture/workorder/2020-07-28/9ihgsqIfzK.png";
			}
			//添加用户
			int doctorId = loginAccountService.add(
					institutionId, name, cell, ossUrl, loginName, loginPass, orgId, isManager, menuIdList);
			ret.put("uuid", WnBizMsgCrypt.encrypt(String.valueOf(doctorId)));
		}
		ret.put("errCode", 1);
		ret.put("errMsg", "操作成功！");
		return ret;
	}

	/**
	 * 修改用户
	 * @return
	 */
	@RequestMapping(value="invs_system_setting.do/updateUser", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> updateUser(HttpSession session,
			@RequestParam("doctorUUID") String doctorUUID,
			@RequestParam("orgId")int orgId,
			@RequestParam("infoImg") String infoImg,
			@RequestParam("name") String name,
			@RequestParam("cell") String cell,
			@RequestParam("loginName") String loginName,
			@RequestParam("loginPass") String loginPass,
			@RequestParam("isManager") int isManager,
			@RequestParam(value="menuIdList[]",required=false) List<Integer> menuIdList) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errCode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		String institutionId = WnSessionUtil.getInstitutionId(session);
		String doctorId = WnBizMsgCrypt.decrypt(doctorUUID);
		Integer supervisorId = WnSessionUtil.getSupervisorId(session);
		//参数校验
		if (cell.length() != 11) {
			ret.put("errMsg", "手机号格式不正确，请输入11位手机号");
			return ret;
		} else if (!ValidateUtil.chkLoginUserPw(loginName)) {
			ret.put("errMsg", "用户名需要由数字/字母/下划线组成");
			return ret;
		}
		int lnLength = loginName.length();
		if (lnLength < 3 || lnLength > 16) {
			ret.put("errMsg", "请输入3-16位用户名");
			return ret;
		} else if (!ValidateUtil.chkLoginUserPw(loginName)) {
			ret.put("errMsg", "用户名需要由数字/字母/下划线组成");
			return ret;
		}
		int pwLength = loginPass.length();
		if(pwLength == 0){
			//不修改密码
			loginPass = null;
		}else if (pwLength < 6 || pwLength > 16) {
			ret.put("errMsg", "请输入6-16位密码");
			return ret;
		} else if (!ValidateUtil.chkLoginUserPw(loginPass)) {
			ret.put("errMsg", "密码需要由数字/字母/下划线组成");
			return ret;
		}
		if(infoImg.indexOf("https://") != -1){
			//不修改头像
			infoImg = null;
		}
		if(menuIdList == null){
			//null表示不做权限菜单相关操作，为空表示全部权限
			menuIdList = new ArrayList<>();
		}
		//权限
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData.getIsManager() == 0) {
			if(!doctorId.equals(supervisorId.toString())){
				//普通用户仅可修改自己
				ret.put("errMsg", "权限不足，无法执行操作");
				return ret;
			}else if(isManager == 1){
				//普通用户不能设置管理员身份
				ret.put("errMsg", "权限不足，无法执行操作");
				return ret;
			}
			menuIdList = null;//普通员工无修改权限
		}else if(loginData.getIsManager() == 1) {
			//获取修改用户等级
			if(loginData.getOrgId() != orgId){
				ret.put("errMsg", "仅能操作所属部门下用户");
				return ret;
			}else if (doctorId.equals(supervisorId.toString())) {
				if(isManager == 0){
					//如果操作的用户的是自己
					ret.put("errMsg", "不能取消自己管理员身份");
					return ret;
				}
				menuIdList = null;//自己的权限无法修改
			}else if (!doctorId.equals(supervisorId.toString())) {
				//如果操作的用户的不是自己
				int userIsManager = dtInvsOrganizationStructureMapper.selectIsManager(institutionId, Integer.parseInt(doctorId));
				if(userIsManager != 0){
					ret.put("errMsg", "不能操作其他管理员");
					return ret;
				}else if(isManager == 1){
					ret.put("errMsg", "权限不足，不能设置管理员");
					return ret;
				}
			}
		}
		DtInvsManageInstitutionSupervisorEntity supervisorEntity = dtInvsManageInstitutionSupervisorMapper.selectByUserName("invs_" + loginName);
		// 账号id是否唯一
		boolean accountUnion = false;
		if (supervisorEntity == null) {
			accountUnion = true;
		} else {
			if (institutionId.equals(supervisorEntity.getInstitutionId()) &&
					doctorId.equals(supervisorEntity.getSupervisorId().toString())) { // self
				accountUnion = true;
			}
		}
		if (!accountUnion) {
			ret.put("errMsg", "用户名已经存在");
			return ret;
		} else {
			if(infoImg != null){
				//图片上传OSS
				infoImg = AliCloudOssUtil.getUrlByBase64(null,infoImg);
				if(infoImg == null || infoImg.length() == 0){
					//默认头像，可替换
					infoImg = "Uploads/Picture/workorder/2020-07-28/9ihgsqIfzK.png";
				}
			}
			//修改用户资料
			loginAccountService.replace(
					institutionId, doctorId, name, cell, infoImg, loginName, loginPass, orgId, isManager, menuIdList);
			ret.put("uuid", WnBizMsgCrypt.encrypt(String.valueOf(doctorId)));
		}
		ret.put("errCode", 1);
		ret.put("errMsg", "操作成功！");
		return ret;
	}

	/**
	 * 删除账户
	 * @param session
	 * @param doctorUUID
	 * @param model
	 * @return
	 */
	@RequestMapping(value="invs_system_setting.do/deleteUser")
	public @ResponseBody Map<String, Object> deleteUser(
			HttpSession session,
			@RequestParam String doctorUUID,
			Model model) {
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errCode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		String doctorId = WnBizMsgCrypt.decrypt(doctorUUID);
		Integer supervisorId = WnSessionUtil.getSupervisorId(session);
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
			ret.put("errMsg", "无法获取到权限，请尝试重新登录");
		} else if (loginData.getIsManager() == 0) {
			ret.put("errMsg", "权限不足，无法执行操作");
		} else if (doctorId.equals(supervisorId.toString())) {
			ret.put("errMsg", "不能删除自己");
		} else {
			if (loginData.getIsManager() == 1) {
				//获取需要删除用户信息
				DtInvsOrganizationStructureStaffEntity entity = dtInvsOrganizationStructureStaffMapper.selectByDoctorId(Integer.parseInt(doctorId));
				if(entity != null && entity.getIsManager() > 0){
					ret.put("errMsg", "权限不足，无法执行操作");
					return ret;
				}
				if(entity != null && entity.getOrg().getId() != loginData.getOrgId()){
					ret.put("errMsg", "仅能操作所属部门下用户");
					return ret;
				}
			}
			String institutionId = WnSessionUtil.getInstitutionId(session);
			if (loginAccountService.remove(institutionId, doctorId) > 0) {
				ret.put("errCode", 1);
			}
		}
		return ret;
	}


	@Inject StaffService staffService = null;
	@Inject OrgService orgService = null;
	@Inject
    DtInvsManageInstitutionMenuMinusMapper dtInvsManageInstitutionMenuMinusMapper = null;
	@Inject
    DtInvsOrganizationStructureMapper dtInvsOrganizationStructureMapper = null;
	@Inject private DtInvsManageInstitutionSupervisorMapper dtInvsManageInstitutionSupervisorMapper = null;
	@Inject private LoginAccountService loginAccountService = null;
	@Inject private DtInvsOrganizationStructureStaffMapper dtInvsOrganizationStructureStaffMapper = null;

}
